#!/usr/bin/perl
use warnings;
use strict;
use LWP::UserAgent;
use Term::ANSIColor qw(:constants);
my $word=join (' ',@ARGV);
# my $word_url=join(' ',@ARGV);
die "没有输入要查询的词\n" if !defined $word;
my $DictDir=$ENV{HOME}."/.lilydict";
my $content;
my $lang;
my $meaning; #释意
my @lines; #读取content的内容
my @origs; #例句 
my @trans;
my $times; #查询次数
if(-e "$DictDir/$word.xml")
{
	#使用本地文件
#	print "使用本地\n"; #For debug
	open(my $DirFileReadHandle,'<', "$DictDir/$word.xml");
	@lines=<$DirFileReadHandle>;
	$content=join(' ',@lines);
	close $DirFileReadHandle;
}
else
{
	# 使用网络
	my $ua = LWP::UserAgent->new;
	my $req=HTTP::Request->new(GET => "http://dict.cn/ws.php?utf8=true&q=$word");
	my $res=$ua->request($req);
	if ($res->is_success) 
		{ $content=$res->content; }
	else 
		{ print $res->status_line, "\n"; }
}
die "查询不到指定单词\n" if ( $content !~ s/<def>(.*)<\/def>/\n/s);
$meaning=$1;
@lines=split('\n', $content);
foreach (@lines)
{
	if(m/<times>([0-9]+)<\/times>/)
		{$times=$1;}
	elsif(m/<lang>(.+)<\/lang>/)
		{$lang=$1;}
	elsif(m/<sent><orig>(.+)<\/orig><trans>(.+)<\/trans><\/sent>/)
	{
		push @origs, $1;
		push @trans, $2;
	}
}
foreach (@origs)
{ s/&lt;em&gt;.*&lt;\/em&gt;/$word/; }

$times=0 if(!defined $times);
$times++;
print STDERR "这个单词已经被查询了", RED, "$times 次!", "\n", RESET  if $times >=3;
print STDOUT BLUE, "$meaning", "\n", RESET;
print "例句:\n" if @origs >=1;
open(my $DirFileWriteHandle,'>', "$DictDir/$word.xml");
print $DirFileWriteHandle "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>", "\n";
print $DirFileWriteHandle "<dict>", "\n" ;
print $DirFileWriteHandle  "<word>$word</word>", "\n";
print $DirFileWriteHandle  "<times>$times</times>", "\n";
print $DirFileWriteHandle  "<lang>$lang</lang>", "\n";
print $DirFileWriteHandle  "<def>$meaning</def>","\n";
while(1)
{
	my $tmp_orig=pop(@origs);
	my $tmp_tran=pop(@trans);
	last if (!defined $tmp_orig);
	print $DirFileWriteHandle "<sent><orig>$tmp_orig</orig><trans>$tmp_tran</trans></sent>","\n";
	print STDOUT RED,"$tmp_orig\t\t" , BLUE, "$tmp_tran\n", RESET;
}
print $DirFileWriteHandle  "</dict>";
close $DirFileWriteHandle;
